import math

from flask import Flask, render_template, request, redirect, url_for
import database

app = Flask(__name__)
DEFAULT_PER_PAGE = 5
ROWS_OPTIONS = [5, 10, 20, 50]  # 可选的每页显示数量


@app.route("/")
def index():
    page = request.args.get("page", 1, type=int)

    # 获取每页显示数量，默认为DEFAULT_PER_PAGE
    per_page = request.args.get("per_page", DEFAULT_PER_PAGE, type=int)

    # 确保per_page是有效的选项
    if per_page not in ROWS_OPTIONS:
        per_page = DEFAULT_PER_PAGE

    messages = database.get_messages(page, per_page)

    # 计算总页数
    total_messages = database.get_total_messages()
    total_pages = math.ceil(total_messages / per_page)  # 向上取整

    return render_template(
        "index.html",
        messages=messages,
        page=page,
        total_pages=total_pages,
        per_page=per_page,
        rows_options=ROWS_OPTIONS,
    )


@app.route("/add", methods=["POST"])
def add_message():
    content = request.form.get("content")
    if content:
        database.insert_message(content)
    return redirect(url_for("index"))


@app.route("/edit/<int:message_id>")
def edit_message(message_id):
    message = database.get_message_by_id(message_id)
    return render_template("edit.html", message=message)


@app.route("/update/<int:message_id>", methods=["POST"])
def update_message(message_id):
    content = request.form.get("content")
    if content:
        database.update_message(message_id, content)
    return redirect(url_for("index"))


@app.route("/delete/<int:message_id>")
def delete_message(message_id):
    database.delete_message(message_id)
    return redirect(url_for("index"))


if __name__ == "__main__":
    app.run(port=8081)
